<template>
  <!-- 头部 -->
  <header class="header">
    <img src="../../assets/logo4.png" alt="Logo" class="logo" />
    <nav class="navbar">
      <div class="user-dropdown">
        <!-- 用户信息下拉 -->
        <div class="user-dropdown" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
          <span class="nav-link user-container">
            <el-icon><User /></el-icon>
            <span>{{ currentUser.school_name }}</span>
          </span>
          <div v-show="showDropdown" class="dropdown-menu">
            <router-link to="/school/user" class="dropdown-item">查看信息</router-link>
            <a href="#" @click.prevent="logout" class="dropdown-item">退出登录</a>
          </div>
        </div>
      </div>
    </nav>
  </header>

  <!-- 主内容区域 -->
  <div style="display: flex">
    <!-- 左侧菜单 -->
    <div style="width: 200px; border-right: 1px solid #ddd; height: calc(100vh - 60px);">
      <el-menu router>
        <el-menu-item index="/school/Home">系统首页</el-menu-item>
        <el-menu-item index="/management/test">数据统计</el-menu-item>
        <el-menu-item index="/management/User">个人信息</el-menu-item>
        <el-menu-item index="/management/Exam">试卷生成</el-menu-item>
        <el-menu-item index="Listener">语音识别</el-menu-item>
        <el-menu-item index="Face">表情分析</el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容 -->
    <div style="flex: 1; width: 0; background-color: #e1e4eb; padding: 10px;">
      <router-view></router-view>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { getToken, parseJwt } from '@/utils/auth'
import router from '@/router/index'

// 响应式状态
const currentUser = ref({})
const showDropdown = ref(false)

// 加载用户信息
const loadUserInfo = () => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      currentUser.value = JSON.parse(userInfoStr)
    } catch (e) {
      console.error('解析用户信息失败', e)
    }
  } else {
    console.warn('⚠️ 无法获取用户信息')
    router.push('/login') // 如果没有 userInfo，跳转到登录页
  }
}

// 登出方法
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  router.push('/login')
}

// 加载学校名称
const loadSchoolName = () => {
  const token = getToken()
  if (!token) {
    console.warn('未登录')
    return
  }

  const userInfo = parseJwt(token)
  if (!userInfo || !userInfo.id) {
    console.warn('用户信息异常')
    return
  }

  const cachedData = JSON.parse(localStorage.getItem('cachedSchoolData'))
  if (cachedData) {
    updateCurrentUserWithSchoolName(cachedData.schoolName)
    return
  }

  axios.get(`/api/school/info/${userInfo.id}`, {
    headers: {
      Authorization: 'Bearer ' + token
    }
  })
    .then(res => {
      if (res.data && res.data.code === 200 && res.data.data) {
        const schoolName = res.data.data.schoolName
        updateCurrentUserWithSchoolName(schoolName)
        localStorage.setItem('cachedSchoolData', JSON.stringify(res.data.data))
      }
    })
    .catch(err => {
      console.error('获取学校名称失败:', err)
    })
}

// 更新 currentUser 方法
const updateCurrentUserWithSchoolName = (schoolName) => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (!userInfoStr) {
    console.warn('⚠️ localStorage 中无 userInfo，无法更新 school_name')
    return
  }

  try {
    const userInfo = JSON.parse(userInfoStr)
    userInfo.school_name = schoolName
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    currentUser.value = userInfo // 整体赋值触发响应式更新
  } catch (e) {
    console.error('更新用户信息失败:', e)
  }
}

// 生命周期钩子
onMounted(() => {
  loadUserInfo()
  if (currentUser.value.role === 'school') {
    loadSchoolName()
  }
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #2c3e50;
  color: white;
}

.logo {
  width: 50px;
  height: auto;
}

.navbar {
  display: flex;
  align-items: center;
  gap: 15px;
  position: relative;
}

.nav-link {
  text-decoration: none;
  color: white;
  font-weight: bold;
  transition: color 0.3s ease;
  cursor: pointer;
}

.user-dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 120px;
}

.dropdown-item {
  display: block;
  padding: 10px 15px;
  text-decoration: none;
  color: #333;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f0f0f0;
}

.user-icon {
  margin-right: 5px;
  font-size: 18px;
  vertical-align: middle;
}

.user-dropdown {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.user-container {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.user-container .el-icon {
  font-size: 18px;
  color: white;
}
</style>